package handles

import (
	"fmt"
	"sync"

	"hawkeye/event"
	"hawkeye/protocol"

	"github.com/panjf2000/gnet/v2"
)

// AuthHandler 认证事件处理器
type AuthHandler struct {
	BaseHandler
	dataType protocol.AuthData
}

// NewAuthHandler 创建认证处理器
func NewAuthHandler(connMutex *sync.RWMutex, connections map[gnet.Conn]string) *AuthHandler {
	return &AuthHandler{
		BaseHandler: BaseHandler{
			connMutex:   connMutex,
			connections: connections,
		},
	}
}

// Handle 处理认证事件
func (h *AuthHandler) Handle(ctx *event.Context, data interface{}) error {
	authData, err := protocol.Convert(data, h.dataType)
	if err != nil {
		return fmt.Errorf("invalid auth data format: %v", err)
	}

	if authData.Token == "" || authData.UserID == "" {
		return fmt.Errorf("invalid auth data: missing token or user_id")
	}

	// 构建报文
	response := &protocol.Message{
		Event: protocol.EventAuth,
		Data:  map[string]interface{}{"status": "success"},
	}

	// 发送心跳响应
	return h.SendMessage(ctx, response)
}
